package com.doraro.coal.moudle.user.controller;

import com.doraro.coal.exception.R;
import com.doraro.coal.moudle.user.model.entity.Organize;
import com.doraro.coal.moudle.user.model.entity.Role;
import com.doraro.coal.moudle.user.model.entity.User;
import com.doraro.coal.moudle.user.model.vo.UserVO;
import com.doraro.coal.moudle.user.service.IOrganizeService;
import com.doraro.coal.moudle.user.service.IUserService;
import com.doraro.coal.service.MailService;
import com.doraro.coal.utils.ShiroUtils;
import com.doraro.coal.utils.WebConstant;
import com.doraro.coal.vo.UserDto;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.mail.MessagingException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Controller
public class MemberController {
    @Autowired
    private IUserService userService;
    @Autowired
    private IOrganizeService organizeService;
    @Autowired
    private MailService mailService;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${coal.url}")
    private String coalUrl;
    /**
     * 用户管理页面
     *
     * @param model
     * @return
     */
    @GetMapping("/member")
    public String getMember(Model model) {
        final Long orgId = ShiroUtils.getUserEntity().getOrganize().getId();
        List<UserVO> result = userService.findAllMember(orgId);
        model.addAttribute("users", result);
        return "member/member";
    }

    /**
     * 个人信息页面
     *
     * @return
     */
    @GetMapping("/person")
    public String person(Model model) {
        final UserDto userEntity = ShiroUtils.getUserEntity();

        final Role role = userEntity.getRole();
        final Organize organize = userEntity.getOrganize();
        model.addAttribute("address", organize.getAddress());
        model.addAttribute("dept", role.getRemark());
        return "member/person";
    }

    /**
     * 企业信息页面
     */
    @GetMapping("/company")
    public String company(Model model) {
        final User userEntity = ShiroUtils.getUserEntity();
        final Organize company = organizeService.getById(userEntity.getOrgId());
        final Organize parent = organizeService.getById(company.getParentId());
        final List<User> users = userService.lambdaQuery().eq(User::getOrgId, company.getId())
                .list();
        final Optional<User> pricinal = users.stream()
                .filter(user -> user.getRoleId().equals(WebConstant.ADMIN_ID)).findFirst();
        if (pricinal.isPresent()) {
            final User user = pricinal.get();
            model.addAttribute("person", user.getNickName());
            model.addAttribute("email", user.getEmail());
            model.addAttribute("phone", user.getMobile());
        }
        model.addAttribute("company", company.getName());
        model.addAttribute("parent", parent.getName());
        model.addAttribute("address", company.getAddress());
        return "member/company";
    }

    /**
     * 用户修改密码
     *
     * @param oldpwd 旧密码
     * @param newpwd 新密码
     * @return
     */
    @PostMapping("/changePwd")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    public R changePwd(@RequestParam String oldpwd, @RequestParam("pwd") String newpwd) {
        if (StringUtils.isBlank(oldpwd)) {
            return R.fail("旧密码不能为空");
        }
        if (StringUtils.isBlank(newpwd)) {
            return R.fail("新密码不能为空");
        }
        final Long userId = ShiroUtils.getUserId();
        final User user = userService.getById(userId);
        if (!StringUtils.equals(user.getPassword(), ShiroUtils.sha256(oldpwd, user.getSalt()))) {
            return R.fail("原始密码不正确");
        }
        final String newSalt = RandomStringUtils.randomAlphanumeric(11);
        userService.lambdaUpdate().eq(User::getUserId, userId)
                .set(User::getSalt, newSalt)
                .set(User::getPassword, ShiroUtils.sha256(newpwd, newSalt))
                .set(User::getStatus, 1)
                .update();
        ShiroUtils.logout();
        return R.success();
    }

    /**
     * 新增用户页面
     *
     * @return
     */
    @GetMapping("/addMember")
    public String goAddMember() {
        return "member/addMember";
    }

    /**
     * 修改用户信息页面
     *
     * @param id
     * @return
     */
    @GetMapping("/updateMember")
    public String goUpdateMember(@RequestParam String id, ModelMap model) {
        User user = userService.getById(id);
        model.addAttribute("updateuser", user);
        return "member/updateMember";
    }

    /**
     * 修改用户密码页面
     *
     * @param id
     * @return
     */
    @GetMapping("/updateMPassword")
    public String goUpdatePassword(@RequestParam String id, ModelMap model) {
        User user = userService.getById(id);
        model.addAttribute("psduser", user);


        return "member/updateMPassword";
    }

    /**
     * 添加用户操作
     * @return
     * @throws IOException
     * @throws TemplateException
     */
    @ResponseBody
    @RequestMapping(value = "/addMember.do", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public R<String> addMemberdo(@RequestBody  Map<String, String> map) throws IOException, TemplateException, MessagingException {
        User user = new User();
        user.setEmail(map.get("email"));
        user.setMobile(map.get("phone"));
        user.setNickName(map.get("nickName"));
        user.setUsername(map.get("userName"));
        user.setStatus(2);
        Long roleId = Long.valueOf(map.get("department"));
        user.setRoleId(roleId);
        user.setSalt(ShiroUtils.getSalt());
        user.setAvatarUrl("http://static.doraro.cn/timg.png");
        User userEntity = ShiroUtils.getUserEntity();
        user.setOrgId(userEntity.getOrgId());
        String password = RandomStringUtils.randomAlphanumeric(6);
        String sha256psd = ShiroUtils.sha256(password, user.getSalt());
        user.setPassword(sha256psd);
        userService.save(user);
        Template template =  freeMarkerConfigurer.getConfiguration().getTemplate("user/emailtemplate.ftl");

        Map<String, String> map2 = new HashMap<>(2);
        map2.put("password", password);
        map2.put("yw","注册");
        map2.put("url", coalUrl);
        String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, map2);
        mailService.sendHtmlMail(map.get("email"), "用户注册", text);


        return R.success("后台录入成功");
    }


    /**
     * 删除用户操作
     * @param id 用户id
     * @return
     */
    @PostMapping("/deleteMember.do")
    @ResponseBody
    public R deleteMember(@RequestParam Long id) {
        userService.removeById(id);
        return R.success();
    }

    /**
     * 修改用户信息操作
     * @param
     * @return
     */
    @PostMapping("/updateMember.do")
    @ResponseBody
    public R<String> UpdateMemberdo(@RequestBody Map<String,String> map) {
        User user = new User();
        Long lid = Long.valueOf(map.get("id"));
        user.setUserId(lid);
        user.setEmail(map.get("email"));
        user.setMobile(map.get("phone"));
        user.setNickName(map.get("nickName"));
        user.setUsername(map.get("userName"));
        Long roleid = Long.valueOf(map.get("department"));
        user.setRoleId(roleid);
        userService.updateById(user);

        return R.success("后台修改成功");
    }


    @PostMapping("/resetPWD.do/{id}")
    @ResponseBody
    public R resetPWD(@PathVariable Long id) throws IOException, TemplateException, MessagingException {

        User user=userService.getById(id);
        user.setSalt(ShiroUtils.getSalt());
        //生成一个6位初始密码
        String password = RandomStringUtils.randomAlphanumeric(6);
        String sha256psd = ShiroUtils.sha256(password, user.getSalt());
        user.setPassword(sha256psd);
        userService.updateById(user);

        //邮件处理
        Template template  = freeMarkerConfigurer.getConfiguration().getTemplate("user/emailtemplate.ftl");

        Map<String, String> map2 = new HashMap<>();
        map2.put("password", password);
        map2.put("yw","修改密码");
        map2.put("url", coalUrl);
        String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, map2);
        mailService.sendHtmlMail(user.getEmail(), "用户修改密码", text);


        return R.success();
    }


}
